<template>
	<view class="main-contain">
		<view>
			<u-sticky bgColor="#2C57F6">
				<u-tabs :list="stickyList" :current="currentTab" :itemStyle="{height:'70px',width:'75px'}"
					:activeStyle="{color:'#FFFFFF'}" @click="handleTabClick" :inactiveStyle="{color:'#000000'}"
					lineWidth="30px"></u-tabs>
			</u-sticky>
		</view>
		<!-- 播放视频 -->
		<view class="video-contain">
			<video :src="bilibiliEmbedUrl" controls autoplay muted @error="handleVideoError"
				@loadedmetadata="handleVideoLoaded"></video>
		</view>
		<!-- 搜索框 -->
		<view class="search-contain">
			<u-search v-model="value" :show-action="false" @change="change" borderColor="#000000"></u-search>
		</view>
		<!-- 小小艺术家的作品列表 -->
		<view class="art-contain">

			<view class="art-item" v-for="(item,index) in filterList" :key="index">
				<view class="art-Img">
					<u-image :src="item.artworkLink" width="100%" height="170rpx" radius="30rpx"
						@click="previewImage(item.artworkLink)"></u-image>
				</view>
				<view class="art-info">名字:{{item.artworkTitle}}</view>
				<view class="art-info">作者:{{item.stuName}}</view>
				<view class="art-info">班级:{{item.claDescribe}}</view>
				<view class="zan-contain">
					<view class="zan-left" @click="handleLike(item)">
						<view class="zan-icon">
							<u-icon :name="item.zanShow?'thumb-up-fill' :'thumb-up'"
								:color="item.zanShow?'red' :'black'" size="32px"></u-icon>
						</view>
						<view class="zan-icon-num">
				
							{{formateNumber(item.likeCount)}}
						</view>
				
					</view>
				</view>
			</view>
			<view class="bottom-contain">
				<u-loadmore :line="true" status="nomore" :nomoreText="nomoreText"></u-loadmore>
			</view>

		</view>

		<tabBar :page="page"></tabBar>
	</view>


</template>

<script>
	import { mapGetters, mapActions } from 'vuex';
	import {
		getAllWorks,userLikeArt
	} from '@/api/artgallery.js'

	export default {
		data() {
			return {
				user:{
					campusId:1,
					parentId:0,
					teacherId:100,
				},
				currentTab: 0,
				emptyMode: 'http://cdn.uviewui.com/uview/empty/data',
				
				baseUrl: 'http://localhost:5217',
				page: "",
				nomoreText: "没有更多了",
				stickyList: [{
						name: '校区作品'
					},
					{
						name: '投票'
					},
					{
						name: '艺术家相册'
					},
					{
						name: '社区'
					},
				],
				bilibiliEmbedUrl: "cloud://cloud1-6gveko5wef73d76d.636c-cloud1-6gveko5wef73d76d-1363348768/video/333.mp4",
				value: '',
				artList: [],
				tarVal: 1,
				filterList: [],

			}
		},
		watch: {
		  activeTab(newVal) {
		    this.currentTab = newVal;
		  }
		},
		created() {
			this.handleAllWorks();
			this.debouncedSearch = this.debounce(this.searchFilter, 600);
		},
		onShow() {
			this.handleAllWorks();
			this.currentTab = this.activeTab;
		},
		 computed: {
		    ...mapGetters(['getActiveTab']),
		    
		    // 简化访问
		    activeTab() {
		      return this.getActiveTab;
		    }
		  },
		methods: {
			...mapActions(['updateActiveTab']),
			//将数量转换成对应的格式（如15080转成1.5万）
			formateNumber(val) {
				const number = parseInt(val, 10);
				if (number >= 10000) {
					return (number / 10000).toFixed(1) + '万';
				}
				return number;
			},
			//点赞
			handleLike(val) {
				console.log(val);
				const data={
						workId:val.artworksId,
					    campusId: this.user.campusId,
					    parentId:this.user.parentId||0,
					    teacherId:this.user.teacherId||0,
				}
				userLikeArt(data).then(res=>{
					console.log(res);
				}).catch(err=>{
					console.log("点赞操作失败");
				})
				if (!val.zanShow) {
					console.log("你点赞了");
					uni.showToast({
					    title: '点赞成功',
					    icon: 'success',
					    duration: 2000,
					    position: 'bottom'
					});
					val.likeCount++;
				} else {
					console.log("你取消了点赞");
					uni.showToast({
					                title: '取消成功',
					                icon: 'success',
					                duration: 2000,
					                position: 'bottom'
					            });
					val.likeCount--;
				}
				val.zanShow=!val.zanShow;
				
			},
			// 防抖函数
			debounce(func, delay) {
				let timer = null;
				return function(...args) {
					if (timer) clearTimeout(timer);
					timer = setTimeout(() => {
						func.apply(this, args);
					}, delay);
				}
			},
			
			// 视频错误处理
			handleVideoError(e) {
				console.error('视频播放错误:', e.detail);
			},
			// 视频加载完成
			handleVideoLoaded() {
				console.log('视频元数据加载完成');
			},
			change(e) {

				this.value = e;
				this.debouncedSearch();
			},
			searchFilter() {
				console.log(this.value);
				const keyword = this.value.trim();
				if (!keyword) {
					this.filterList = [...this.artList];
					this.nomoreText = "没有更多了";
					return;
				}
				this.filterList = this.artList.filter(item => {
					const titleMatch = item.artworkTitle.includes(keyword);
					const authorMatch = item.stuName.includes(keyword);
					const classMatch = item.claDescribe.includes(keyword);
					return titleMatch || authorMatch || classMatch;
				});
				console.log("列表的长度为:" + this.filterList.length);
				if (this.filterList.length < 1) {
					this.nomoreText = "暂无数据";
				}
			},

			//获取校区所有作品
			handleAllWorks() {
				const data = {
					campusId: this.user.campusId,
					parentId: this.user.parentId||0,
					teacherId:this.user.teacherId||0,
				}
				getAllWorks(data)
					.then(res => {
						console.log(res);
						this.artList = res.data.artworkInfoList.map(item => {
						        return {
						          ...item,
						          // 直接转换为布尔值
						          zanShow: item.zanShow === 'true'
						        };
						      });
						this.filterList = [...this.artList];
					}).catch(err => {
						console.error('获取作品失败:', err)
					})
			},
			//图片预览
			previewImage(imgUrl) {
				const allImages = this.filterList.map(item => item.artworkLink);
				uni.previewImage({
					current: imgUrl,
					urls: allImages
				});
			},
			// 标签跳转方法
			    handleTabClick(e) {
			      const tabIndex = e.index;
			      this.updateActiveTab(tabIndex); // 更新 Vuex 状态
			      
			      if (tabIndex === 1) { // 点击"投票"标签
			      	console.log("跳转投票");
			      	uni.navigateTo({
			      		url: '/pages/voting event/voting event'
			      	});
			      } else if (tabIndex ===2 ) {
			      	console.log("跳转艺术家相册");
			      	uni.navigateTo({
			      		url: '/pages/art-album/art-album'
			      	});
			      }else if(tabIndex === 3){
					console.log("跳转社区");
					uni.navigateTo({
						url: '/pages/community/community'
					});
				}
			    },
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-tabs__wrapper__nav__line {
		background-color: white !important;
		z-index: 1;
	}

	::v-deep .u-tabs__wrapper__nav__line__bar {
		background-color: #1989FA;
		z-index: 2;
	}

	.main-contain {
		padding-bottom: 120px;
		box-sizing: border-box;

		.sticky-contain {}

		.video-contain {
			height: 400rpx;
			padding: 20rpx 30rpx;
			position: relative;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

			// 视频组件样式
			video {
				width: 100%;
				height: 100%;
				background-color: #000;
			}

		}

		.search-contain {
			padding: 30rpx 100rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
			border-radius: 60rpx;
			overflow: hidden;
		}

		.art-contain {
			box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);

			.art-item {
				width: calc(50% - 20rpx);

				display: inline-block;
				margin: 10rpx;
				margin-bottom: 0;
				border-radius: 20rpx;
				box-sizing: border-box;
				border: 1px solid black;
				box-shadow: 0 15rpx 50rpx rgba(0, 0, 0, 0.2),
					0 5rpx 15rpx rgba(0, 0, 0, 0.15),
					5rpx 5rpx 15rpx rgba(0, 0, 0, 0.1);
				background-color: #fff;
				overflow: hidden;

				.art-Img {
					height: 50%;
					margin: 5rpx;
					border-radius: 30rpx;
					overflow: hidden;
					box-shadow:
						0 8rpx 30rpx rgba(0, 0, 0, 0.25),
						inset 0 0 15rpx rgba(0, 0, 0, 0.15);

				}

				.art-info {
					height: 40rpx;
					overflow: hidden;
					line-height: 40rpx;
					padding-left: 10%;
					margin-bottom: 15rpx;

					white-space: nowrap;
					text-overflow: ellipsis;
					width: 90%;
				}
				.zan-contain {
					height: 80rpx;
					box-sizing: border-box;
					margin: 0 20rpx 15rpx 20rpx;
				
					.zan-left {
						width: 100%;
						height: 100%;
						display: flex;
						justify-content: center;
						align-items: center;
						overflow: hidden;
						.zan-icon {
							width: 20%;
							height: 100%;
							display: flex;
							justify-content: center;
							align-items: center;
				
						}
				
						.zan-icon-num {
							width: 30%;
							height: 100%;
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}
				}
			}

			.bottom-contain {}
		}


	}
</style>